#include <pthread.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#define NUM_THREADS 20

int file;
pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER;

void* run_thread(void* arg)
{
  int thread_id; char i;
  pthread_mutex_lock(&mut);
  for (i = 'A'; i < 'Z'; i++) {
    write(file, &i, 1);
    usleep(1);
  }
  write(file, "\n", 1);
  pthread_mutex_unlock(&mut);
  return 0;
}

int main(int argc, char* argv[])
{
  int i;
  pthread_t threads[NUM_THREADS];
  file = open("tmp.txt", O_CREAT|O_TRUNC|O_WRONLY);
  for(i = 0; i < NUM_THREADS; i++) {
    pthread_create(&threads[i], 0, run_thread, 0);
  }

  for(i = 0; i < NUM_THREADS; i++) {
    pthread_join(threads[i], 0);
  }
  close(file);
  return 0;
}
